//
//  SubmitPictureViewController.swift
//  Gaoloumi
//
//  Created by Jasper on 4/17/16.
//  Copyright © 2016 Jasper. All rights reserved.
//

import UIKit
import SVProgressHUD
import ImagePicker
import TZImagePickerController
import AVOSCloud

class SubmitPictureViewController: RootViewController, ImagePickerDelegate, UITextViewDelegate, TZImagePickerControllerDelegate {
    
    @IBOutlet weak var picNameTextFiled: UITextField!
    @IBOutlet weak var describeTextView: UITextView!
    @IBOutlet weak var addButton: UIButton!
    
    @IBOutlet weak var lineHeight: NSLayoutConstraint!
    @IBOutlet weak var lineHeight2: NSLayoutConstraint!
    @IBOutlet weak var viewHeight: NSLayoutConstraint!
    
    var imagePickerController:ImagePickerController?
    var buttonImg: UIImage?
    
    var selectedPhotos = [UIImage]()
    var selectedAssets = [AnyObject]()
    
    // 外面传入
    var tower: Tower?
    
    let contantHeight = UIScreen.main.bounds.height-64+1
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "提交\"\((tower?.name)!)\"图片"
        lineHeight.constant = 0.5
        lineHeight2.constant = 0.5
        view.backgroundColor = UIColor.white
        describeTextView.placeholder = "图片描述(选填)"
        describeTextView.delegate = self;
        viewHeight.constant = contantHeight
    }

    @IBAction func addClicked(_ sender: UIButton) {
        presentImagePicker()
    }
    
    func presentImagePicker() {
        
//        if self.imagePickerController == nil {
//            self.imagePickerController = ImagePickerController()
//            self.imagePickerController?.delegate = self
//            self.imagePickerController?.imageLimit = 1
//        }
//        dispatch_async(dispatch_get_main_queue(), {
//            self.presentViewController(self.imagePickerController!, animated: true, completion: nil)
//        })
        
        
        let imagePickerVc = TZImagePickerController(maxImagesCount: 1, delegate: self)
        
        imagePickerVc?.selectedAssets = NSMutableArray(array: selectedAssets)
        imagePickerVc?.allowPickingVideo = false
        imagePickerVc?.allowPickingOriginalPhoto = false
        
        self.present(imagePickerVc!, animated: true) {}
    }
    
    // MARK: TZImagePickerControllerDelegate
    
    private func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [AnyObject]!, isSelectOriginalPhoto: Bool) {
        selectedPhotos = photos
        selectedAssets = assets
        
        let img = photos.first
        if img != nil {
            buttonImg = img!
        } else {
            buttonImg = nil
        }
        refreshButtons(selectedPhotos)
    }
    
    private func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [AnyObject]!, isSelectOriginalPhoto: Bool, infos: [[AnyHashable: Any]]!) {
        
    }
    
    func imagePickerControllerDidCancel(_ picker: TZImagePickerController!) {
        
    }
    
    private func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingVideo coverImage: UIImage!, sourceAssets asset: AnyObject!) {
        
    }
    
    // MARK://
    func refreshButtons(_ images: [UIImage]) {
        
        let img = images.first
        if img != nil {
            addButton.setBackgroundImage(img, for: UIControlState())
        }
    }
    
    @IBAction func submitClicked(_ sender: UIBarButtonItem) {
        picNameTextFiled.resignFirstResponder()
        describeTextView.resignFirstResponder()

        if buttonImg == nil {
            SVProgressHUD.showError(withStatus: "请选择图片")
            return
        }
        SVProgressHUD.show()
        let picture = Picture()
        picture.user = AVUser.current()
        picture.isShow = false
        if picNameTextFiled.text == nil || (picNameTextFiled.text?.isEmpty)! {
            picture.name = tower?.name
        } else {
            picture.name = picNameTextFiled.text
        }
        picture.descriptions = describeTextView.text
        
        let data = UIImageJPEGRepresentation(buttonImg!, 0.7)
        picture.file = AVFile(data: data!)
        picture.tower = tower
        
        picture.saveInBackground { (succed: Bool, error: Error?) in
            if succed {
                self.navigationController?.popViewController(animated: true)
                SVProgressHUD.showSuccess(withStatus: "提交成功，等待审核，预计12小时内生效")
            } else {
                SVProgressHUD.showError(withStatus: error?.localizedDescription)
            }
        }
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if textView.text.characters.count + text.characters.count > 500 {
            SVProgressHUD.showError(withStatus: "最多输入500个字")
            return false
        }
        return true
    }
    
    @IBAction func tapGesture(_ sender: UITapGestureRecognizer) {
        picNameTextFiled.resignFirstResponder()
        describeTextView.resignFirstResponder()
    }
    
    // MARK: ImagePickerDelegate
    func wrapperDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) {
        
    }
    func doneButtonDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) {
        imagePickerController?.dismiss(animated: true, completion: nil)
        let img = images.first
        if img != nil {
            buttonImg = img!
        } else {
            buttonImg = nil
        }
        
        refreshButtons(images)
    }
    func cancelButtonDidPress(_ imagePicker: ImagePickerController) {
        
    }
}
